# -*- coding:utf-8 -*-
# @Time: 2021/3/28 13:33
# @Author: Zhanyi Hou
# @Email: 1295752786@qq.com
# @File: vars_stack.py
import logging
from typing import Dict, List, Any, Tuple

logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                    datefmt='%a, %d %b %Y %H:%M:%S', filemode='w')

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)


class CallStack:
    def __init__(self):
        self.requestReturn: bool = False
        self.frames: List[Tuple[str, Dict[str, Any]]] = [("GLOBAL", {})]
        self.returnVars: List[Any] = []

    def globalFrame(self):
        return self.frames[0]

    def currentFrame(self):
        return self.frames[-1]

    def getVar(self, varName: str) -> Any:
        try:
            return self.currentFrame()[1][varName]
        except KeyError as e:
            logger.fatal("堆栈帧：%s,变量名称%s" % (self.frames, varName))
            raise e

    def setVar(self, varName: str, value: Any):
        self.currentFrame()[1][varName] = value

    def addFrame(self, funcName, variables: Dict[str, Any]):
        self.frames.append((funcName, variables))

    def popFrame(self):
        self.frames.pop(-1)
        self.requestReturn = False

    def setReturnVars(self, vars: List[Any]):
        self.returnVars = vars

    def getReturnVars(self) -> List[Any]:
        ret = self.returnVars
        self.returnVars = []
        return ret
